<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <div class='wrapper'></div>
    <script>
        /*
            3、 减少dom操作
            comment: changeLikeText中需要自己处理dom，将dom操作改为重新调用render生成新dom，页面自动替换dom
            todo:  抽象公共组件
        */

        const createDOMFromString = (domString) => {
            const div = document.createElement('div')
            div.innerHTML = domString
            return div
        }

        class LikeButton {

            constructor() {
                this.state = { isLiked: false }
            }

            setState(state) {
                const oldEl = this.el
                this.state = state
                this.el = this.render()
                if (this.onStateChange) {
                    this.onStateChange(oldEl, this.el)
                }
            }

            changeLikeText() {
                this.setState({
                    isLiked: !this.state.isLiked
                })
            }

            render() {
                this.el = createDOMFromString(` 
                    <button class='like-button'> 
                        <span class='like-text'>
                            ${this.state.isLiked ? '取消' : '点赞'}
                            </span> 
                        <span>👍</span> 
                    </button> 
                `)
                this.el.addEventListener('click', this.changeLikeText.bind(this), false)
                return this.el
            }
        }

        const wrapper = document.querySelector('.wrapper')

        const likeButton1 = new LikeButton()
        wrapper.appendChild(likeButton1.render()) // 第⼀次插⼊DOM 元素

        likeButton1.onStateChange = (oldEl, newEl) => {
            wrapper.insertBefore(newEl, oldEl) // 插⼊新的元素
            wrapper.removeChild(oldEl) // 删除旧的元素
        }

        const likeButton2 = new LikeButton()
        wrapper.appendChild(likeButton2.render()) // 第⼀次插⼊DOM 元素

        likeButton2.onStateChange = (oldEl, newEl) => {
            wrapper.insertBefore(newEl, oldEl) // 插⼊新的元素
            wrapper.removeChild(oldEl) // 删除旧的元素
        }

    </script>
</body>

</html>